package com.google.code.hibernate.rest.impl;

import static com.google.code.hibernate.rest.internal.InternalPreconditions.checkNotNull;

import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * @author wangzijian
 * 
 */
class Classes {

	private static final Map<Class<?>, Class<?>> primitiveToWrapper = new HashMap<Class<?>, Class<?>>(8);
	static {
		primitiveToWrapper.put(Boolean.class, boolean.class);
		primitiveToWrapper.put(Byte.class, byte.class);
		primitiveToWrapper.put(Character.class, char.class);
		primitiveToWrapper.put(Double.class, double.class);
		primitiveToWrapper.put(Float.class, float.class);
		primitiveToWrapper.put(Integer.class, int.class);
		primitiveToWrapper.put(Long.class, long.class);
		primitiveToWrapper.put(Short.class, short.class);
	}

	private Classes() {
	}

	static Object stringToRequiredType(String string, Class<?> requiredType) throws IllegalArgumentException {
		if (string == null) {
			return null;
		}
		checkNotNull(requiredType, "requiredType");
		if (requiredType.equals(String.class)) {
			return requiredType.cast(string);
		}
		PropertyEditor propertyEditor = findPropertyEditor(requiredType);
		checkNotNull(propertyEditor, 
				"Registered PropertyEditor not found by requried type " + requiredType.getName());
		propertyEditor.setAsText(string);
		return propertyEditor.getValue();
	}

	private static PropertyEditor findPropertyEditor(Class<?> requiredType) {
		Class<?> primitiveType = primitiveToWrapper.get(requiredType);
		if (primitiveType != null) {
			return PropertyEditorManager.findEditor(primitiveType);
		} else {
			return PropertyEditorManager.findEditor(requiredType);
		}
	}

}
